$(function() {
    //探针日志
    //----Hbase访问日志
    /**
     * Init
     *
     *
     * |--
     * |   `--
     * |   `--
     * |	   `--
     * |		   `--
     * |		   `--
     * |			   `--
     * |		   `--
     * |--
     * |--
     */
    var ad = appData();

    var tmplObj = null;
    var arryAll = 0; //判断个数
    var idName = []; //动态id名
    var arry1 = [],
        arry2 = [],
        arry3 = [],
        arry4 = [],
        arry5 = [],
        arry6 = [],
        arry7 = [];
    var bigArry = [arry1, arry2, arry3, arry4, arry5, arry6, arry7];
    var marks = []; //动态mark标记后台返回
    var newLis = [] //用戶點擊顯示與否
    var keyTypeName = []
    var firstShow = 0 //判断是否是第一次进入页面
    var keyIndex = 0
    var yesIs = true //判断是否是高级搜索的检索
    var currentPage=0;
    var leftName = temp.logTitleArr();
    var EnName = ['HbaseFWRZ', 'SolrFWRZ', 'MySQLFWRZ', 'MongoDBFWRZ', 'FTPCJRZ',
        'JTTMHbase', 'JTTMSolr', 'JTTMMySql', 'DTTMMySql', 'WJJTTM', 'WJDTTM',
        'YWCZRZ',
        'JGPTRZ', 'TZSBRZ', 'TMSBRZ', 'YWSBRZ'
    ]
    var pageType = '';

    DomNameStart()

    function DomNameStart() {
       // $(".advanced-search").toggle(200);
        $("#achieve").on("click", function() {
            currentPage=0
            firstShow = 1
            showTable(true, 1, false)

        })
        //侧面添加class索引加载
        //if(!$.getUrlParam("id")) {

        $("#HBs").length == 1 ? $('.sys-sidebar ul li').eq(0).find('ul li ').eq(0).addClass('active') : ''
        //子选项第一个需注释掉

        var name = $('.sys-sidebar').find('li .active a').text()

        //			if(==0){
        //				pageType= 'HbaseFWRZ'
        //			}
        pageType = EnName[leftName.indexOf(name)]
        console.log(pageType)
        $("#TopName").text(name) //替换头部日志名称
        //}

        ad.selectList('HBASE_DATA_TOP', {
            "pageType": pageType
        }, function(data) {

            loadDom2(data.keyType, "#keyType", false)
            keyTypeList(data.keyType, "#keyListVal")
            loadDom2(data.other[0], "#result", true)

            $("#topBody").empty()

            function spanList(data) {
                var str = ''
                for(var i = 0; i < data.length; i++) {
                    str += `<span style=${i==0?"margin-left:-3px":''}><input type="text" mark="${data[i].mark}" placeholder="${data[i].name}" val="${data[i].value}"></span>`
                }
                return str
            }
            $("#topBody").append(`<div class="as-item">
              <div class="as-item-tit">关键词</div>
              <div class="as-item-con" id="spansList">
                ${spanList(data.keyType)}
              </div>
            </div>`)

            for(var i = 0; i < data.list.length; i++) {

                function lengths() {
                    var length = data.list[i].value.length
                    var strings = '';
                    for(var j = 0; j < length; j++) {
                        strings += `<li><a href="javascript:void(0)" title="${data.list[i].value[j].titles?data.list[i].value[j].titles:""}" data-id="${data.list[i].value[j].values}";>${data.list[i].value[j].names}</a></li>`
                    }
                    return strings
                }

                arryAll += 1
                idName.push(data.list[i].stringId)
                marks.push(data.list[i].mark)
                temp.type0("#topBody", data.list[i], lengths(), i)

            }
            $(".advanced-search").toggle(200);
            domCase()
            sessionCon()
        })
        if(!$.getUrlParam("id")) {
            temp.setInitTime();
            showTable(true, 1, false)
        }

        $.daterRangeDefine("#DateRange")
        $("#DateRange").attr('readonly', 'readonly').css('width', '340px')

        $.daterRangeDefine("#DateRange_2")
        $("#DateRange_2").attr('readonly', 'readonly').css('width', '340px')

    }

    function keyTypeList(data, id) {
        $(id).empty()
        for(var i = 0; i < data.length; i++) {

            $(id).append(`<li class="clickHide"><input type="text" class="clickHide" mark="${data[i].mark}" value="" val="${data[i].value}" placeholder="${data[i].name}" title="${data[i].name}"></li>`)

            keyTypeName.push(data[i].value)
        }
        $(id).find('li').eq(0).hide()
        $("#searchVal").attr('placeholder', $(id).find('li').eq(0).find('input').attr('title'))
    }

    function domCase() {
        $("#searchVal").focus(function() {
            $(this).siblings('.fm-group-list').slideDown(400)
        })

        $('body').on('click', function(e) {

            if($(e.target).hasClass('clickHide')) {

            } else {
                $('.fm-group-list').slideUp(400)
            }

        })
        $("#keyType").change(function() {

            let removeIndex = keyTypeName.indexOf($(this).val())
            let valueName = $(this).find('option:selected').text()

            keyIndex = removeIndex

            $("#searchVal").attr('placeholder', valueName)

            $("#keyListVal li").eq(removeIndex).hide().siblings().show()

        })

        $("#search1").off('click').on('click', function() {
            currentPage=0
            $(this).next().slideDown(400);
            var searchVal = $("#searchVal").val()
            firstShow = 1
            showTable(true, 1, true)

        })

        var idArry = []
        bigArry.splice(arryAll)

        for(var i = 0; i < $(".as-item").length; i++) {
            if($(".as-item").eq(i).find('ul').attr('id')) {
                idArry.push("#" + $(".as-item").eq(i).find('ul').attr('id'))
            }

        }

        for(var i = 0; i < arryAll; i++) {

            addDomName(idArry[i])

        }

        function addDomName(id) {
            $(id).on('click', 'li', function() {
                var index = $(this).parent().attr('indexs')

                bigArry[index] = []
                var _this = $(this);

                if(_this.hasClass('active')) {

                    _this.removeClass('active')
                    bigArry[index] = []
                } else {
                    _this.addClass('active').siblings().removeClass('active')
                    bigArry[index].push(_this.find('a').attr('data-id'))

                }

                console.log(bigArry)

            })

        }

    }
    //表格show加载
    function showTable(dontRenderPager, page, all) {

        ad.insert("MYSQL_DATA_LIST", createParam(page, all), function(data) {

            $("#tableBody").empty();
            $("#tableTr").empty().append(`<th class="field no-sort" width="60"><a class="colbtn no-sort" href="javascript:void(0)"><i class="icon-eye-o"></i></a>
	              <ul class="field-list" id="tbList" >
	              	
	              </ul>
	            </th>`);
            if(data.length === 0) {
                $("#tableBody").append("<tr><td colspan='3' class='colspanCss'><h1>暂无数据</h1></td></tr>");
                return false;
            }
            for(var i = 0; i < data.tableHead.length; i++) {

                $("#tbList").append(`<li class="checked">${data.tableHead[i]}</li>`)
                $("#tableTr").append(`<th>${data.tableHead[i]}</th>`)
            }

            for(var i = 0; i < data.content.length; i++) {

                $("#tableBody").append(`<tr><td>${i+currentPage+1}</td>${lengthsTable(i,data)}</tr>`)

            }

            if(dontRenderPager) {
                renderPager(data.totalRecord);
            }
            tableCut(data.display)

            for(var i = 0; i < $("#tableBody tr").length; i++) {
                $("#tableBody tr").eq(i).find('td').eq(2).on('click', function() {
                    //	console.log()
                    var ids = $(this).siblings().eq(1).text()
                    var time = $(this).siblings().eq($(this).siblings().length-1).text()

                    $(this).parents('tr').addClass('active').siblings().removeClass('active')
                    addAlerts("LOG_DATA_PROP1", '#alertBody', {
                        "id": ids,
                        "pageType":pageType,
                        "time":time
                    })

                })
            }

            //$('table').tablesort().data('tablesort')

            //表格排序
            $('.pagination li:last').remove()
        })
    }

    function renderPager(totalRecord, nowPage) {
        $("div.page").pagination(totalRecord, appApi("PAGE_SIZE"), {
            callback: function(page_id, jq) {
                pageNumNow1 = page_id + 1;
                currentPage=appApi('PAGE_SIZE')*page_id;
                showTable(false, pageNumNow1, yesIs);
            }
        }, nowPage);
    };

    function lengthsTable(i, data) {
        var length = data.content[0].length
        var strings = '';
        var td1 = ['查询', '删除', '新增', '修改']

        var td2 = ['成功', '失败']

        var td3 = ['高风险', '中风险', '低风险','其他','一般风险']

        for(var j = 0; j < length; j++) {

            if(td1.indexOf(data.content[i][j]) != -1) {
                if(td1.indexOf(data.content[i][j]) != 0) {
                    strings += `<td title="${data.content[i][j]}"><span class="fc-danger">${data.content[i][j]}</span></td>`
                } else {
                    strings += `<td title="${data.content[i][j]}"><span class="">${data.content[i][j]}</span></td>`

                }

            } else if(td2.indexOf(data.content[i][j]) != -1) {
                if(td2.indexOf(data.content[i][j]) == 0) {
                    strings += `<td title="${data.content[i][j]}"><span class="badge badge-success">${data.content[i][j]}</span></td>`
                }
                if(td2.indexOf(data.content[i][j]) == 1) {
                    strings += `<td title="${data.content[i][j]}"><span class="badge badge-danger">${data.content[i][j]}</span></td>`
                }
            } else if(td3.indexOf(data.content[i][j]) != -1) {
                if(td3.indexOf(data.content[i][j]) == 0) {
                    strings += `<td title="${data.content[i][j]}"><span class="badge fc-danger">${data.content[i][j]}</span></td>`
                }
                else if(td3.indexOf(data.content[i][j]) == 1) {
                    strings += `<td title="${data.content[i][j]}"><span class="badge fc-warning">${data.content[i][j]}</span></td>`
                }
                else if(td3.indexOf(data.content[i][j]) == 2) {
                    strings += `<td title="${data.content[i][j]}"><span class="badge fc-warning">${data.content[i][j]}</span></td>`
                }else {
                    strings += `<td title="${data.content[i][j]}"><span  class="badge ">${data.content[i][j]}</span></td>`
                }
            } else {
                var strs = `<td title="${data.content[i][j]}">${data.content[i][j]}</td>`;
                if(j==1){
                    strs = `<td title="${data.content[i][j]}"><a href="javascript:void(0)">${data.content[i][j]}</a></td>`;
                }
                strings += strs
            }

        }
        return strings
    }
    //数据的下载
    $("#loadLog").on("click", function() {

        uploadingFile()

    })

    //数据载入按钮
    function uploadingFile() {

        $.downloadInterface($.getRadParamUrl(appApi("T_UPLOADING_FILE")), "post", createParam(false, yesIs, true));
    };

    function tableCut(hideArrys) {
        newLis = hideArrys;
        for(var i = 0; i < $("#tbList li").length; i++) {

            $("#tbList li").eq(i).removeClass('checked')
            var col_index = i + 1
            $("table").find("thead th:eq(" + col_index + ")").hide();
            $("table").find("tr").each(function() {
                $(this).children("td:eq(" + col_index + ")").hide();
            });

            if(hideArrys.indexOf(i) != -1) {
                $("#tbList li").eq(i).addClass('checked')
                var col_index = i + 1
                $("table").find("thead th:eq(" + col_index + ")").show();
                $("table").find("tr").each(function() {
                    $(this).children("td:eq(" + col_index + ")").show();
                });
            }

        }

        $(".field").on("click", "a", function() {
            $(this).next("ul").slideToggle(200);

        })
        $(".field").on("click", "li", function() {

            var col_index = $(this).index() + 1;
            var col_index2 = $(this).index()
            newLis.indexOf(col_index2) == -1 ? newLis.push(col_index2) : newLis.splice(newLis.indexOf(col_index2), 1);

            var table = $(this).parents("table");
            if($(this).hasClass('checked')) {
                if($(this).parent().find(".checked").length < 4) {
                    _as.jAlert("最少保留显示3个字段")
                    // alert("最少保留显示3个字段");
                    return
                }
                $(this).removeClass('checked')
                table.find("thead th:eq(" + col_index + ")").hide();
                table.find("tr").each(function() {
                    $(this).children("td:eq(" + col_index + ")").hide();
                });
            } else {
                $(this).addClass('checked')
                table.find("thead th:eq(" + col_index + ")").show();
                table.find("tr").each(function() {
                    $(this).children("td:eq(" + col_index + ")").show();
                });
            }
        })

        $("#asbtn").off('click').on("click", function() {
            yesIs = !yesIs
            $(".filter").toggle()
            $("em", this).hasClass('open') ? $("em", this).removeClass('open') : $("em", this).addClass('open');
            $(".advanced-search").toggle(200);
        })

    }

    function loadDom(api, id, val) {
        ad.selectList(api, {}, function(data) {
            if(val == '') {
                $(id).empty()
            } else {
                $(id).empty().append("<option value='-1'> " + val + "</option>")
            }
            for(var i = 0; i < data.length; i++) {
                $(id).append("<option  value='" + data[i].id + "'>" + data[i].value + "</option>")
            }

        })
    }

    function loadDom2(data, id, a) {

        $(id).empty()

        if(a) {
            //给结果下拉框添加stingId
            $(id).attr('stId', data.stringId)

            for(var i = 0; i < data.value.length; i++) {
                $(id).append("<option  mark='" + data.mark + "' value='" + data.value[i].values + "'>" + data.value[i].names + "</option>")
            }
        }
        if(!a) {
            for(var i = 0; i < data.length; i++) {
                $(id).append("<option mark='" + data[i].mark + "' value='" + data[i].value + "'>" + data[i].name + "</option>")
            }
        }

    }

    function createParam(page, all, loadUp) {
        var keyWords = []
        var timeRange = ''

        if(all) {

            timeRange = $("#DateRange").val()
            keyWords.push({
                "value": $("#searchVal").val(),
                "mark": $("#keyType option:selected").attr('mark'),
                "stringId": $("#keyType").val()
            }) //输入框的值特定添加
            console.log(1)
            for(var i = 0; i < $("#keyListVal input").length; i++) { //普通检索
                var index = $("#keyListVal input").eq(i)
                if(i != keyIndex) {
                    keyWords.push({
                        "value": index.val(),
                        "mark": index.attr('mark'),
                        "stringId": index.attr('val')
                    })
                }

            }
        } else {
            timeRange = $("#DateRange_2").val()
            for(var i = 0; i < $("#spansList input").length; i++) { //高级检索
                var index = $("#spansList input").eq(i)
                keyWords.push({
                    "value": index.val(),
                    "mark": index.attr('mark'),
                    "stringId": index.attr('val')
                })
            }
        }

        var top1 = {

            "dateRange": timeRange, //时间范围
            //			"keyType":[$("#keyType").val(),$("#keyType").find("option:selected").attr('mark')],//keyType
            //			"keyValue":$("#searchVal").val()//查询关键词
            "keyWords": keyWords

        }

        var top2 = []
        for(var i = 0; i < idName.length; i++) {

            var obj = {
                name: idName[i],
                val: bigArry[i],
                mark: marks[i]
            }

            top2.push(obj)

        }
        //top3的值
        //		var inputsVal = []
        //		for(var i=0;i<$("#backVal input").length;i++){
        //
        //
        //			var val = $("#backVal").find("input").eq(i).val()
        //			if(val==null){
        //				val=""
        //			}
        //			inputsVal.push(val)
        //
        //		}
        var top3 = {

            "result": [
                [
                    $("#result").attr('stId') == null ? '' : $("#result").attr('stId'), $("#result").val() == null ? '' : $("#result").val(), $("#result option").attr('mark') == null ? '' : $("#result option").attr('mark')
                ]
            ], //返回结果
            //"value":[{"flag":"ROW_NUM","val":inputsVal}],///返回值

        }
        var params = {
            "page": page,
            "top1": top1,
            "top2": top2,
            "top3": top3,
            "showNum": newLis,
            "firstShow": firstShow,
            "pageType": pageType,
            "pageSize": appApi('PAGE_SIZE')
        }
        if(all) {
            params = {
                "page": page,
                "top1": top1,
                //			"top2":top2,
                //			"top3":top3,
                "showNum":newLis,
                "firstShow": firstShow,
                "pageType": pageType,
                "pageSize": appApi('PAGE_SIZE')
            }
        }
        if(loadUp) {
            if(yesIs) {
                params = {
                    "top1": top1,
                    "page": page,
                    "showNum": newLis,
                    "pageSize": appApi('PAGE_SIZE'),
                    "pageType": pageType

                }
            } else {
                params = {
                    "page": page,
                    "showNum": newLis,
                    "pageSize": appApi('PAGE_SIZE'),
                    "top1": top1,
                    "top2": top2,
                    "top3": top3,
                    "pageType": pageType

                }
            }

        }
        return params
    }

    function addAlerts(api, id, param) {

        ad.selectList(api, param, function(data) {
            function aryys(datas) {
                var str = '';
                for(var i = 0; i < datas.length; i++) {
                    str += "<span class='badge'>" + datas[i] + "</span>"
                }
                return str

            }
            $(id).empty().append(temp.atm(data,1))

            $("#info").show()
            $("#closees").on('click', function() {
                $("#info").hide()
            })
        })

    }

    function sessionCon() {

        var sikpUrl = $.getUrlParam('id')
        var clusterId = $.getUrlParam('clusterId')
        var Date_day = $.getUrlParam('day')
        var Date_time = $.getUrlParam('hour')
        var time = ''
        if(Date_day&&Date_time){
            time = Date_day+' '+Date_time.split('-')[0]+'-'+Date_day+' '+Date_time.split('-')[1]
        }else if(Date_day&&!Date_time){
            time = Date_day+' 00:00 '+'- '+Date_day+' 23:59'
        }

        history.pushState(null, '', 'index.html')
        if(sikpUrl&&clusterId) {
            $("#topBody li a[data-id=" + sikpUrl + "]").parent().addClass('active')
            $("#topBody li a[data-id=" + clusterId + "]").parent().addClass('active')
            for(var i = 0; i < $("#topBody li").length; i++) {

                if($("#topBody li").eq(i).hasClass('active')) {

                    var index = $("#topBody li").eq(i).parent().attr('indexs')
                    var val = $("#topBody li").eq(i).find('a').attr('data-id')
                    bigArry[index].push(val)

                }
            }

            $("#DateRange_2").val(time)
            $("#DateRange").val(time)

            showTable(true, 1, false)
            $(".filter").toggle()
            $(".advanced-search").toggle(200);
            yesIs = !yesIs //判断是否是高级搜索的检索
        }

    }
})